package com.cloudfun.campusshare.device.protocol.command;

import com.cloudfun.campusshare.common.constant.Code;
import com.cloudfun.campusshare.common.exception.BusinessException;
import com.cloudfun.campusshare.util.ByteUtil;
import io.netty.util.CharsetUtil;
import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;

/**
 * Created by Huqin on 2020/1/15
 */
public class CommandFactory {

    public Frame typeIdQuery() {
        return new Frame((byte) 112, new byte[]{});
    }

    public Frame query() {
        return new Frame((byte) 1, ByteUtil.hexStringToByte("4d01"));
    }

    public Frame start() {
        return new Frame((byte) 1, ByteUtil.hexStringToByte("4d04"));
    }

    public Frame pause() {
        return new Frame((byte) 1, ByteUtil.hexStringToByte("4d05"));
    }

    public Frame reset() {
        return new Frame((byte) 1, ByteUtil.hexStringToByte("4d0A"));
    }

    public Frame verifyCode(String verifyCode) {
        if (StringUtils.isBlank(verifyCode) || verifyCode.length() != 4) {
            throw new BusinessException(Code.ERROR, "验证码错误");
        }
        byte[] bytes = verifyCode.getBytes(CharsetUtil.UTF_8);
        return new Frame((byte) 1, ByteUtil.merge(Arrays.asList(ByteUtil.hexStringToByte("5d1d"), bytes)));
    }

    public Frame alarmQuery() {
        byte[] command = ByteUtil.hexStringToByte("73");
        return new Frame(command[0], new byte[]{});
    }

    /**
     * 组命令
     *
     * @param subCommandType
     * @param params
     * @return
     */
    public Frame groupCommand(byte[] subCommandType, byte[] params) {
        byte[] payload = new byte[subCommandType.length + params.length];
        System.arraycopy(subCommandType, 0, payload, 0, subCommandType.length);
        System.arraycopy(params, 0, payload, subCommandType.length, params.length);
        return new Frame(ByteUtil.hexStringToByte("60")[0], payload);
    }
}
